package com.ccl.iot.dialogs;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.ccl.iot.template.ActivityDialogTitled;
import com.ccl.iot.publics.Messager;
import com.ccl.iot.publics.Res;
import com.ccl.iot.publics.Window;
import com.ccl.iot.IOTNetAPI;
import com.ccl.iot.IOTNetAPIEnum.ESECURITY_INFO_TYPE;
import com.ccl.iot.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 忘记密码的dialog
 */
public class ForgetPwdDialog extends ActivityDialogTitled {

	private boolean mIsRemember = false;

	private TextView tvEmail;

	private EditText mEtUserName;

	private EditText mEtUserEmail;

	private Button mBtnConfirm;

	private Button mBtnCancel;

	private LinearLayout mLLUserName;

	public LinearLayout mByAnswerContainer;
	public LinearLayout mBySecurityContainer;

	private int STATE_INPUT_BASEINFO = 0;
	private int STATE_INPUT_ANSWER = 1;
	private int STATE_INPUT_SECURITYCODE = 2;

	private int currentState = STATE_INPUT_BASEINFO;

	private EditText mEtNewPwd;

	private EditText mEtCheckPwd;

	private String mUserName;

	private String mUserEmail;

	private EditText mEtInputCode;

	private IOTNetAPI mApi;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setBackable(true);
		setTitle(R.string.Title_forgetpwd);
		init();
		initData();
		initListener();
	}

	private void init() {
		setContentView(R.layout.dialog_forget_password);
		mLLUserName = (LinearLayout) findViewById(R.id.ll_forget_pwd_username);
		
		mByAnswerContainer = (LinearLayout) findViewById(R.id.ll_byAnswer_container);
		mBySecurityContainer = (LinearLayout) findViewById(R.id.ll_bySecurityCode_container);

		tvEmail = (TextView) findViewById(R.id.tv_email);

		mEtUserName = (EditText) findViewById(R.id.et_user_name);
		mEtUserEmail = (EditText) findViewById(R.id.et_user_email);

		mBtnConfirm = (Button) findViewById(R.id.bt_input_confirm);
		mBtnCancel = (Button) findViewById(R.id.bt_input_cancel);

		mEtNewPwd = (EditText) findViewById(R.id.et_new_pwd);
		mEtCheckPwd = (EditText) findViewById(R.id.et_check_pwd);
	}

	private void initData() {
		Intent intent = getIntent();
		
		//是否忘记了忘记密码问题的回答,如果忘记了就要通过邮箱改密码,否则通过忘记密码问题修改
		mIsRemember = intent.getBooleanExtra("isRemember", false);
		String userName = intent.getStringExtra("userName");
		
		//修改密码之前是否有输入用户名,如果有输入则弹出此dialog时自动填入
		if (!TextUtils.isEmpty(userName)) {
			mEtUserName.setText(userName);
		}

		mApi = IOTNetAPI.GetInstance();
	}

	private void initListener() {
		
		mEtUserName.requestFocus();
		Window.ShowInputDialog(getContext());	//打开软键盘

		//监听两个edittext框,如果两个edittext都有输入文本则确认按钮可用,否则不可用
		handleUsefulInfoChange(mEtUserName);
		handleUsefulInfoChange(mEtUserEmail);

		mBtnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		if (!mIsRemember) {
			bySecurityCode();		//通过验证码修改密码
		} else {
			mBtnConfirm.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					//通过忘记密码来修改密码,需要用户先输入用户名和注册时的邮箱
					mUserName = mEtUserName.getText().toString().trim();
					mUserEmail = mEtUserEmail.getText().toString().trim();
					
					if(!checkEmail(mUserEmail)){
						Messager.Show(Res.GetString(getContext(), R.string.EmailError), 0);
						return;
					}
					
					//获取用户的忘记密码问题
					String question = mApi.getFPQuestion(mUserName, mUserEmail);
					if(TextUtils.isEmpty(question)){
						Messager.Show(Res.GetString(getContext(), R.string.UserErrorOrEmailError), 0);
						return;
					}

					//把界面换成修改密码的界面
					mLLUserName.removeAllViews();
					byAnswer(question);
				}
			});
		}

	}

	private void bySecurityCode() {
		currentState = STATE_INPUT_SECURITYCODE;
		mBtnConfirm.setOnClickListener(null);
		mBtnConfirm.setEnabled(false);
		mBySecurityContainer.setVisibility(View.VISIBLE);

		mEtInputCode = (EditText) findViewById(R.id.et_input_code);
		handleUsefulInfoChange(mEtInputCode);

		Button btGetCode = (Button) findViewById(R.id.btn_getcode);

		HandlerButtton(btGetCode);
	}

	private void byAnswer(String question) {
		currentState = STATE_INPUT_ANSWER;
		mBtnConfirm.setOnClickListener(null);
		mByAnswerContainer.setVisibility(View.VISIBLE);

		TextView tvQuestion = new TextView(getContext());
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		mLLUserName.addView(tvQuestion, params);

		tvEmail.setText(R.string.Caption_FPAnswer);

		mEtUserEmail.setText("");
		mEtUserEmail.setHint("");
		
		mEtUserEmail.requestFocus();
		Window.ShowInputDialog(getContext());
		Window.ShowInputDialog(getContext());

		handleUsefulInfoChange(mEtCheckPwd);
		handleUsefulInfoChange(mEtNewPwd);
		
		// Toast.makeText(getContext(), "..."+question, 0).show();
		question = Res.GetString(getContext(), R.string.Caption_FPQuestion) + "" + question;
		tvQuestion.setText(question);
		tvQuestion.setTextColor(Color.BLACK);

		mBtnConfirm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String newPwd = mEtNewPwd.getText().toString().trim();

				if (!TextUtils.isEmpty(newPwd) && newPwd.equals(mEtCheckPwd.getText().toString().trim())) {
					if (mApi.changePasswordByAnswer(mUserName, mEtUserEmail.getText().toString().trim(), newPwd)) {
						Messager.Show(Res.GetString(getContext(), R.string.ModifySuccess), 0);
						finish();
					} else {
						Messager.Show(Res.GetString(getContext(), R.string.AnswerError), 0);
					}
				} else {
					Messager.Show(Res.GetString(getContext(), R.string.CheckError), 0);
				}
			}
		});
	}

	private void handleUsefulInfoChange(EditText aInfo) {
		if (aInfo != null) {
			aInfo.addTextChangedListener(new TextWatcher() {
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				}

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
				}

				@Override
				public void afterTextChanged(Editable s) {
					mBtnConfirm.setEnabled(isInfoValid());
				}
			});
		}
	}

	private boolean isInfoValid() {
		if (currentState == STATE_INPUT_BASEINFO) {
			return !TextUtils.isEmpty(mEtUserName.getText().toString().trim()) && !TextUtils.isEmpty(mEtUserEmail.getText().toString().trim());
		} else if (currentState == STATE_INPUT_ANSWER) {
			return !TextUtils.isEmpty(mEtUserEmail.getText().toString().trim()) && !TextUtils.isEmpty(mEtNewPwd.getText().toString().trim())
					&& !TextUtils.isEmpty(mEtCheckPwd.getText().toString().trim());
		} else {
			return !TextUtils.isEmpty(mEtInputCode.getText().toString().trim()) && !TextUtils.isEmpty(mEtUserName.getText().toString().trim()) && !TextUtils.isEmpty(mEtUserEmail.getText().toString().trim());
		}
	}

	private void HandlerButtton(final Button btn) {
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mUserEmail = mEtUserEmail.getText().toString().trim();

				if(!checkEmail(mUserEmail)){
					Messager.Show(Res.GetString(getContext(), R.string.EmailError), 0);
					return;
				}

				btn.setEnabled(false);
				CountDownTimer timer = new CountDownTimer(60000, 1000) {

					@Override
					public void onTick(long millisUntilFinished) {
						btn.setText(millisUntilFinished / 1000 + "");
					}

					@Override
					public void onFinish() {
						btn.setEnabled(true);
						btn.setText(R.string.RegetSecurityCode);
					}
				};
				
				//获取验证码按钮的定时器
				timer.start();

				if (mApi.getSecurityCode((short) 2052, ESECURITY_INFO_TYPE.ESECURITY_INFO_TYPE_EMAIL, mUserEmail)) {
					Messager.Show(Res.GetString(getContext(), R.string.SecurityCodePrompt), 0);
				}
			}

		});

		mBtnConfirm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mUserName = mEtUserName.getText().toString().trim();
				try {
					int safeCode = Integer.parseInt(mEtInputCode.getText().toString().trim());
					//通过验证码自动修改密码,并把新的密码发到用户邮箱
					if (mApi.resetPassword((short) 2052, ESECURITY_INFO_TYPE.ESECURITY_INFO_TYPE_EMAIL, mUserName, mUserEmail, safeCode)) {
						Messager.Show(Res.GetString(getContext(), R.string.MidifyPwdSuccess), 0);
						finish();
					}else{
						Messager.Show(Res.GetString(getContext(), R.string.SecurityCodeErrorOrUserError), 0);
					}
				} catch (Exception e) {
					Messager.Show(Res.GetString(getContext(), R.string.SecurityCodeError), 0);
				}
			}
		});
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}
	
	/**
	 * 通过正则表达式验证邮箱格式是否正确
	 * @param email	邮箱
	 * @return
	 */
	private boolean checkEmail(String email) {
		String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		Pattern regex = Pattern.compile(check);
		Matcher matcher = regex.matcher(email);
		return matcher.matches();
	}

}
